import { reqLogin, reqLogout, reqUserInfo } from '@/api/user'
import { defineStore } from 'pinia'
import type { LoginFrom, LoginData } from '@/api/user/type'
import type { userState } from './type'
import { getToken, removeToken, setToken } from '@/utils/token'
import routes from '@/router/staticRoutes'

const useUserStore = defineStore('User', {
  state: (): userState => {
    return {
      token: getToken(),
      Routes: routes,
      userInfo: {
        name: '',
        avatar: '',
        routes: [],
        buttons: [],
        roles: []
      }
    }
  },
  actions: {
    // 登录
    async login(state: LoginFrom) {
      const res: LoginData = await reqLogin(state)
      if (res.code === 20000) {
        console.log(res)

        this.token = res.data.token as string
        setToken(res.data.token as string)
        return res
      } else {
        return Promise.reject(new Error(res.data.message))
      }
    },

    // 获取用户信息
    async getUserInfo() {
      const res = await reqUserInfo()
      if (res.code === 20000) {
        this.userInfo = res.data
      }
      return res
    },

    // 退出登录
    async logout() {
      const res = await reqLogout()
      if (res.code === 20000) {
        this.token = null
        this.userInfo = {
          name: '',
          avatar: '',
          routes: [],
          buttons: [],
          roles: []
        }
        removeToken()
        return res
      }
    }
  },
  getters: {}
})

export default useUserStore
